package com.db.test.controller;

import com.db.test.vo.FileVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;


@Controller
@RequestMapping("/load")
public class FileController {
    private static  String path = "D://file";

    @RequestMapping(value = "/download")
    public String download(){
        return "download.html";
    }

    @PostMapping(value = "/downLoadFilePost")
    @ResponseBody
    public void downLoadFilePost(FileVo file, HttpServletResponse response) {
        String filePath = path+ File.separatorChar+file.getFileName();

        File entityFile = new File(filePath);
        if(entityFile.exists()){
            try {
                FileInputStream inputStream = new FileInputStream(entityFile);
                response.setContentType("application/force-download");
                response.setCharacterEncoding("utf-8");
                response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getFileName().getBytes(), "ISO-8859-1"));
                OutputStream os = response.getOutputStream();
                byte[] bytes = new byte[1024];
                int n = 0;
                while((n = inputStream.read(bytes)) != -1){
                    os.write(bytes,0,n);
                }
                inputStream.close();
                os.flush();
                os.close();
            }catch(Exception e){
            }
        }
    }


    @GetMapping(value = "/downLoadFileGet")
    @ResponseBody
    public void downLoadFileGet(@RequestParam("filename") String fileName, HttpServletResponse response) {
        String filePath = path+ File.separatorChar+fileName;

        File entityFile = new File(filePath);
        if(entityFile.exists()){
            try {
                FileInputStream inputStream = new FileInputStream(entityFile);
                response.setContentType("application/force-download");
                response.setCharacterEncoding("utf-8");
                response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes(), "ISO-8859-1"));
                OutputStream os = response.getOutputStream();
                byte[] bytes = new byte[1024];
                int n = 0;
                while((n = inputStream.read(bytes)) != -1){
                    os.write(bytes,0,n);
                }
                inputStream.close();
                os.flush();
                os.close();
            }catch(Exception e){

            }
        }
    }

}
